package test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class IdNumberAge {

    public static void main(String[] args) {
        String idCard = "130429200003090874";
        String age = calculateAge(idCard);
        System.out.println(age);
    }


    public static String calculateAge(String idCard) {
        try {
            // 截取身份证中的出生年月日
            String birthdayStr = idCard.substring(6, 14);
            // 将出生年月日字符串转为日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthday = sdf.parse(birthdayStr);

            // 获取当前日期
            Date now = new Date();

            // 计算年龄
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(birthday);
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(now);
            int age = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
            if (cal2.get(Calendar.MONTH) < cal1.get(Calendar.MONTH)
                    || (cal2.get(Calendar.MONTH) == cal1.get(Calendar.MONTH)
                    && cal2.get(Calendar.DAY_OF_MONTH) < cal1.get(Calendar.DAY_OF_MONTH))) {
                age--;
            }

            return age + "";
        } catch (ParseException e) {
            e.printStackTrace();
            return "未知";
        }
    }

}
